<?php

class GroupController extends Buzz_AuthedController {

    private $gmapper = null;
    private $authChecker;

    public function init() {
        $this->gmapper = new Application_Model_GroupMapper();
        $this->authChecker = new Buzz_AuthChecker();
    }

    public function doPreDispatch() {
        $action = $this->getRequest()->getActionName();
        if ($action == "edit" || $action == "delete") {
            $id = $this->getRequest()->getParam("id");
            if (!$this->authChecker->ownsGroup($id)) {
                throw new Exception("Action forbidden. You do not own this group.");
            }
        }
    }

    public function viewAction() {
        $user = Zend_Auth::getInstance()->getIdentity();
        $id = $this->getRequest()->getParam("id");
        $this->view->subscribed = $this->gmapper->is_user_subscribed($user->id(), $id);
        $this->view->gid = $id;
        $this->view->error = null;
        $group = $this->gmapper->find($id);

        if ($group == null) {
            $this->view->error = "Inexistent group with id $id";
        } else {
            $this->view->isOwner = $this->authChecker->ownsGroup($group);
            $this->view->group = $group;
            $elements = $this->gmapper->find_element_list($group->id(), $this->session->filter);
            $this->view->elements = $elements;
        }
    }

    public function editAction() {
        $group = $this->gmapper->find($this->getRequest()->getParam("id"));
        if ($group != null) {
            $desc = $this->getRequest()->getParam("description");
            $this->view->description = $desc;
            $group->set_description($desc);
            $this->gmapper->save($group);
            $this->_helper->json(array("description" => $desc));
        }
    }

    public function subscribeAction() {
        $gid = $this->getRequest()->getParam("id");
        $uid = Zend_Auth::getInstance()->getIdentity()->id();
        $this->gmapper->add_subscription($gid, $uid);
        $this->_helper->json(array("subscribed" => true));
    }

    public function unsubscribeAction() {
        $gid = $this->getRequest()->getParam("id");
        $uid = Zend_Auth::getInstance()->getIdentity()->id();
        $this->gmapper->del_subscription($gid, $uid);
        $this->_helper->json(array("subscribed" => false));
    }

    public function deleteAction() {
        $gid = $this->getRequest()->getParam("id");
        $user = Zend_Auth::getInstance()->getIdentity();
        $group = $this->gmapper->find($gid);

        if (!$group) {
            throw new Exception("This group does not exist.");
        }

        $this->_helper->json(array("success" => $this->gmapper->remove($gid) == 1));
    }

    public function listAction() {
        $groups = $this->gmapper->fetchAll($this->session->filter);
        $this->view->groups = $groups;
    }

    public function createAction() {
        $req = $this->getRequest();
        if (!$req->isPost()) {
            $url = $this->view->url(array(), "newgroup", true);
            $this->view->form = new Application_Form_GroupCreate(array('action' => $url));
            return $this->render('create');
        }

        $form = new Application_Form_GroupCreate();
        if (!$form->isValid($req->getPost())) {
            $this->view->form = $form;
            return $this->render('create');
        }

        $imgType = $req->getParam("imageType");
        if ($imgType == "upload") {
            if (!$form->imageUpload->receive()) {
                throw new Exception("Error during file upload. Please try again.");
            }
        }

        $imgpath = null;
        if ($imgType != "none") {
            $url = ($imgType == "url")
                   ? $req->getParam("imageUrl")
                   : $form->imageUpload->getFilename();

            $imageInDb = new Application_Model_Image(null, $url);
            $imgmapper = new Application_Model_ImageMapper();
            $imageId = $imgmapper->save($imageInDb);
            $dlproxy = Buzz_DownloadProxy::instance();
            $key = $dlproxy->requestImageDownload($url, $imageId);
        }

        $newGroup = new Application_Model_Group(null, $req->getParam("name"), false,
                $imageId, $req->getParam("description"), $this->view->user->id());
        $this->gmapper->save($newGroup);
        $this->_redirect($this->view->url(array(), "grouplist", true));
    }
}